package com.kj.tms.system.controller;


import com.kj.tms.common.bean.dto.ReturnData;
import com.kj.tms.common.bean.exception.BusinessException;
import com.kj.tms.common.bean.session.SessionManager;
import com.kj.tms.common.utils.IpUtil;
import com.kj.tms.common.utils.StringUtil;
import com.kj.tms.common.utils.constant.Consts;
import com.kj.tms.common.utils.encrypt.MD5Util;
import com.kj.tms.pri.system.basicinfo.dto.TaxPayersInfoDto;
import com.kj.tms.pri.system.basicinfo.service.TaxPayersInfoService;
import com.kj.tms.pri.system.org.dto.OrgDto;
import com.kj.tms.pri.system.user.dto.UserDto;
import com.kj.tms.pri.system.user.service.UserService;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wzl on 2017/10/12.
 * 用户登录
 */
@Controller
@RequestMapping("/system/register")
public class LoginController {

    private static Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private UserService userServiceImpl;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private TaxPayersInfoService taxPayersInfoServiceImpl;

    /**
     * 进入到用户登录页面
     *
     * @return 登录page
     */
    @RequestMapping(value = "/toLogin")
    public ModelAndView toLogin(Model model) {
        ModelAndView mv;
        logger.info("#################sessison id :" + sessionManager.getId());
        if (sessionManager.getAttribute(Consts.CUR_USER_ORG_CODE) != null) {
            JSONObject jsonObject = JSONObject.fromObject(sessionManager.getAttribute(Consts.USER));
            model.addAttribute("userInfo", jsonObject);
            mv = new ModelAndView("system/index");
        } else {
            mv = new ModelAndView("system/login");
        }
        return mv;
    }

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @param request  请求对象
     * @return ReturnData
     * @throws Exception
     */
    @RequestMapping("/login")
    @ResponseBody
    public ReturnData login(@RequestParam(value = "username", required = false) String username,
                            @RequestParam(value = "password", required = false) String password,
                            HttpServletRequest request) throws Exception {
        logger.info("###############sessison id :" + sessionManager.getId());
        try{
            List<OrgDto> orgDtos = userServiceImpl.login(
                    IpUtil.getIpAddr(request), username, MD5Util.getMD5Code(password));
            if (orgDtos.size() > 1) {
                return new ReturnData(Consts.SUCCESS, "登陆成功！", orgDtos);
            } else if (orgDtos.size() == 1) {
                Map  map =new HashMap();
                map.put("orgCode",orgDtos.get(0).getOrgCode());
                map.put("orgName",orgDtos.get(0).getOrgName());
                return new ReturnData(Consts.SINGLE_ORG_SUCCESS, "登陆成功！",map);
            } else {
                return new ReturnData(Consts.ERROR, "登陆失败！");
            }
        }catch (Exception e){
            return new ReturnData(Consts.ERROR, "登陆失败！"+e.getMessage(),e.getMessage());
        }



    }

    /**
     * @method      [loginFrame]
     * @description [跳转登陆主页]
     * @author      王国庆
     * @version     1.0
     * @param       orgIdCode  机构编码
     * @param       orgName    机构名称
     * @return
     * @exception
     * @date        2017年10月27日 11:41
     */
    @RequestMapping(value = "/loginFrame")
    public String loginFrame(Model model,
                             @RequestParam(value = "orgIdCode",required = false) String orgIdCode,
                             @RequestParam(value = "orgName",required = false) String orgName) {
        try {
            UserDto user = userServiceImpl.loginIndex(orgIdCode,orgName);
            List<TaxPayersInfoDto> taxPayersInfoDtoList =
                    taxPayersInfoServiceImpl.queryListByOrgCode(orgIdCode);
            //当前登录机构纳税主体信息放入session   CUR_USER_ORG_TAX_PAYERS_INFO
            sessionManager.setAttribute(Consts.CUR_USER_ORG_TAX_PAYERS_INFO, taxPayersInfoDtoList);
            JSONObject jsonObject = JSONObject.fromObject(user);
            model.addAttribute("userInfo", jsonObject);
        }catch (Exception e){
            return "redirect:/system/register/toLogin";
        }

        return "system/index";
    }

    /**
     * @method      [orgCodeChange]
     * @description [更改用户机构]
     * @author      王国庆
     * @version     1.0
     * @param       curOrgCode 当前登陆机构
     * @return
     * @exception
     * @date        2018年11月07日 10:44
     */
    @RequestMapping("/orgCodeChange")
    @ResponseBody
    public ReturnData orgCodeChange(@RequestParam(value = "curOrgCode", required = false) String curOrgCode) {
        UserDto user = (UserDto) sessionManager.getAttribute(Consts.USER);
        if (StringUtil.isNull(user)) {
            return new ReturnData("9999", "系统超时，请重新登录。");
        }
        user.setCurUserOrgCode(curOrgCode);
        //根据机构ID 人员ID 查询 角色信息等
        try {
            userServiceImpl.changeOrgCode(user);
            //当前登录机构纳税主体信息放入session   CUR_USER_ORG_TAX_PAYERS_INFO
            //通过当前机构查询当前纳税主体信息
            List<TaxPayersInfoDto> taxPayersInfoDtoList = taxPayersInfoServiceImpl.queryListByOrgCode(curOrgCode);
            sessionManager.setAttribute(Consts.CUR_USER_ORG_TAX_PAYERS_INFO, taxPayersInfoDtoList);
            logger.info("存入当前机构编码CUR_USER_ORG_TAX_PAYERS_INFO：[" + sessionManager.getAttribute(Consts.CUR_USER_ORG_TAX_PAYERS_INFO).toString() + "]");
        } catch (Exception e) {
            if (e instanceof BusinessException) {
                return new ReturnData(Consts.NO_ROLE_ORG_USER, "该机构下的用户没有分配角色！", "");
            }
        }
        return new ReturnData(Consts.SUCCESS, "登陆成功！", "");
    }

    /**
     * @method      [logout]
     * @description [用户退出]
     * @author      王国庆
     * @version     1.0
     * @param
     * @return
     * @exception
     * @date        2017年11月07日 10:44
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ModelAndView logout() {
        // 清空session进行用户的退出，跳出登录，给出提示信息
        sessionManager.invalidate();
        ModelAndView mv = new ModelAndView("system/login");
        return mv;
    }
}